package a14_Sort.Compare;

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;

/**
 * @Author quan
 * @Description TODO
 * @Date 2023/4/3 11:22
 */
//比较器对象
class StudentAgeSec implements Comparator<Student>{
    @Override
    public int compare(Student o1, Student o2) {
        return o2.age - o1.age;//取小用大堆，该写顺序
    }
}
public class Student{
//public class Student implements Comparable<Student>{
    String name;
    int age;
    public Student(){};
    public Student(String name, int age){
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
//    @Override
//    public int compareTo(Student o) {
//        return o.age - this.age;
//    }
    public static void main(String[] args) {
        Student s1 = new Student("A",21);
        Student s2 = new Student("B",25);
        Student s3 = new Student("H",19);
        Student s4 = new Student("K",31);
        Student s5 = new Student("C",26);
        Student[] students = {s1,s2,s3,s4,s5};
        //--------------------Comparable接口方式---------------------------
//        System.out.println(s1.compareTo(s2));
        //比较s1与s2,s1-s2<0，表明s1指向的对象小于s2的对象
        //----------------------------------比较器方式---------------------
        //现在要获取年纪最小的两个学生
//        Queue<Student> queue = new PriorityQueue<>();
        Queue<Student> queue = new PriorityQueue<>(new StudentAgeSec());
        for (Student student: students) {
            queue.offer(student);
            if(queue.size() > 2){
                queue.poll();
            }
        }
        System.out.println(queue);
        /*for (Student student: students) {
            if(queue.size() < 3){
                queue.offer(student);
            }else{//Step2
                if(student.age < queue.element().age){
                    queue.poll();
                    queue.offer(student);
                }
            }
        }
        System.out.println(queue);*/
    }

}

////使用比较器创建最小堆
//class LessIntCompSmall implements Comparator<Integer>{
//    @Override
//    public int compare(Integer o1, Integer o2) {
//        return o1 - o2;
//    }
//}
////使用比较器创建最大堆
//class LessIntCompBig implements Comparator<Integer>{
//    @Override
//    public int compare(Integer o1, Integer o2) {
//        return o2 - o1;
//    }
//}